package com.sky.service.impl.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.BaseException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.admin.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.admin.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


import java.util.List;

import java.util.Objects;

@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 使用MD5加密明文密码进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (Objects.equals(employee.getStatus(), StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }


    @Override
    public Result editPassword(PasswordEditDTO passwordEdit) {
        // 将用户的旧密码和新密码加密成密文
        passwordEdit.setOldPassword(DigestUtils.md5DigestAsHex(passwordEdit.getOldPassword().getBytes()));
        passwordEdit.setNewPassword(DigestUtils.md5DigestAsHex(passwordEdit.getNewPassword().getBytes()));

        Employee employee = employeeMapper.selectById(passwordEdit.getEmpId().intValue());

        // 旧密码错误
        if (!passwordEdit.getOldPassword().equals(employee.getPassword()))
            return Result.error(MessageConstant.PASSWORD_ERROR);

        int rows = employeeMapper.updatePasswordByid(passwordEdit);
        // 更改密码失败
        if (rows == 0) return Result.error(MessageConstant.PASSWORD_EDIT_FAILED);

        return Result.success();
    }

    @Override
    public Employee getEmployeeById(Integer id) {
        Employee employee = employeeMapper.selectById(id);
        if (employee == null) throw new BaseException(MessageConstant.USER_NOT_LOGIN);
        employee.setPassword("");
        return employee;
    }

    @Override
    public Result<PageResult> getEmployeeByPage(EmployeePageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        List<Employee> employeeServiceList = employeeMapper.selectByPageAndKeywords(dto.getName());

        PageInfo<Employee> pageInfo = new PageInfo<>(employeeServiceList);

        PageResult result = new PageResult(pageInfo.getTotal(),employeeServiceList);

        log.info("员工分页返回数据为：{}" ,result);

        return Result.success(result);
    }

    @Override
    public Result addEmployee(EmployeeDTO dto) {
        // 对象属性值拷贝
        Employee employee  = new Employee();
        BeanUtils.copyProperties(dto,employee);

        // 设置属性
        employee.setStatus(StatusConstant.ENABLE);
        //TODO: 密码加密
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        if (employeeMapper.insertEmployeeInfo(employee) == 0) return Result.error("增加员工信息失败");

        return Result.success();
    }

    @Override
    public Result updateEmployeeById(Employee employee) {


         if(employeeMapper.updateEmployee(employee) == 0) throw new BaseException("修改失败");

         return Result.success();

    }

    @Override
    public Result setEmployeeStatusById(Integer status, Integer id) {
        if(employeeMapper.setEmployeeStatusById(status,id) == 0) throw new BaseException("修改员工状态失败");

        return Result.success();

    }


}
